#include "stdafx.h"
#include "CollaborationChannel.h"

CCollaborationChannel::~CCollaborationChannel(void)
{
}

CCollaborationChannel::CCollaborationChannel(QString user):m_user(user)
{
	
}

void CCollaborationChannel::SkipReview(int diff)
{
	// TODO: NYI
}

void CCollaborationChannel::ReviewEdit(int diff, bool vandalism)
{
	// TODO: NYI
}

QHostAddress CCollaborationChannel::GetHost() const
{
	QHostInfo irc = QHostInfo::fromName("irc.freenode.net");
	return irc.addresses().first(); // TODO: Pick one better than this
}

unsigned short CCollaborationChannel::GetPort() const
{
	return 6667;
}

void CCollaborationChannel::ProcessIncomingCommand(QString command)
{
	static QRegExp privmsgRegex("^:([^!]+)![^@]+@[^\\s]+\\s+PRIVMSG\\s+([^\\s]+)\\s+:(.+)$");
	static QRegExp flaggedRegex("^![Ff][Ll][Aa][Gg] (\\d+) ([\\?\\d\\.]+)(?: REM (.+))?[\\s\\r\\n]*$");

	// Was it a message?
	if (privmsgRegex.indexIn(command) >= 0)
	{
		QString sender = privmsgRegex.cap(1);
		QString target = privmsgRegex.cap(2);
		QString msg = privmsgRegex.cap(3);

		// Which command was it?
		if (flaggedRegex.indexIn(msg) >= 0)
		{
			// !FLAG diff probability REM remark
			unsigned int diff = flaggedRegex.cap(1).toUInt();
			QString probabilityString = flaggedRegex.cap(2);
			float probability; 
			if (probabilityString == "???")
				probability = -1.0f;
			else
				probability = probabilityString.toFloat();

			QString remark;

			if (flaggedRegex.captureCount() > 2)
				remark = flaggedRegex.cap(3).trimmed();

			emit FlagEdit(diff, probability, sender, remark);
		}
	}

}

QString CCollaborationChannel::GetChannel() const
{
	return "#CollabRC";
}

QString CCollaborationChannel::GetUser() const
{
	return m_user;
}


void CCollaborationChannel::AcceptChange( CRecentChange* change )
{
	QString command;
	QTextStream stream(&command);
	stream << "PRIVMSG #CollabRC :!WILLREVIEW " << change->GetDiff() << " " << change->GetRandomID();
	QueueCommand(command);
}

void CCollaborationChannel::MarkBad( unsigned int diff )
{
	QString command;
	QTextStream stream(&command);
	stream << "PRIVMSG #CollabRC :!BAD " << diff;
	QueueCommand(command);
}

void CCollaborationChannel::MarkGood( unsigned int diff )
{
	QString command;
	QTextStream stream(&command);
	stream << "PRIVMSG #CollabRC :!GOOD " << diff;
	QueueCommand(command);
}